package com.springboot.mall.controller;

import com.github.pagehelper.PageInfo;
import com.springboot.mall.common.ApiRestResponse;
import com.springboot.mall.common.Constant;
import com.springboot.mall.exception.MallException;
import com.springboot.mall.exception.MallExceptionEnum;
import com.springboot.mall.model.request.AddProductRequest;
import com.springboot.mall.model.request.UpdateProductRequest;
import com.springboot.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

/*
 *后台商品管理控制器
 *
 *@data 2022-05-12
 */
@Controller
public class ProductAdminController {

    @Autowired
    private ProductService productService;

    @PostMapping("/admin/product/add")
    @ResponseBody
    public ApiRestResponse addProduct(@Valid @RequestBody AddProductRequest addProductRequest){
        productService.addProduct(addProductRequest);
        return ApiRestResponse.success();
    }

    //图片上传
    /*
    * 实现逻辑：
    * 将上传的file获取，获取它的整体文件名
    * 然后通过这个整体的文件名截取.后面的文件类型
    * 通过UUID生成一个新的文件名前缀
    * UUID和文件类型组装成一个新的唯一的file文件
    * 创建文件：
    * 定义一个文件夹用来保存file（配置地址）
    *生成文件
    *
    *
    * */

    @PostMapping("/admin/upload/file")
    @ResponseBody
    public ApiRestResponse upload(HttpServletRequest httpServletRequest,@RequestParam("file") MultipartFile file){
        //获取文件原始全名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
       String suffixName =  originalFilename.substring(originalFilename.lastIndexOf("."));
       //生成UUID
        UUID uuid = UUID.randomUUID();
        //合并成新的文件名
        String newFileName = uuid.toString() + suffixName;
        //文件上传的地址(创建文件夹)
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        //目标文件
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()){
            if (!fileDirectory.mkdir()){
                throw new MallException(MallExceptionEnum.MKDIR_FAILED);
            }
        }
        //传过来的file写到刚刚定义好的destfile中去
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //把文件地址返回去
        try {
            return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL()+"")) + "/images/" + newFileName);
        } catch (URISyntaxException e) {
            throw new MallException(MallExceptionEnum.UPLOAD_FAILED);
        }
        //"localhost:8083/images/a4541c02-2c11-4d24-8528-14eb932c7f36.jpeg"

        //return ApiRestResponse.success(httpServletRequest.getRequestURI() + "/images/" + newFileName);
        //"/admin/upload/file/images/a4541c02-2c11-4d24-8528-14eb932c7f36.jpeg"
        //return ApiRestResponse.success(httpServletRequest.getRequestURL() + "/images/" + newFileName);
        //"localhost:8083/admin/upload/file/images/a4541c02-2c11-4d24-8528-14eb932c7f36.jpeg"
        /*
        * 因此一定要调用下面的方法，提取出主机端口等信息即可，然后拼接出最后的图片路径
        *
        *
        * */
    }

    //获取IP的端口号
    private URI getHost(URI uri){
        URI effectivURI;
        try {
            effectivURI = new URI(uri.getScheme(),
                    uri.getUserInfo(),
                    uri.getHost(),
                    uri.getPort(),null,null,null);
        } catch (URISyntaxException e) {
            effectivURI = null;

        }
        return effectivURI;
    }

    @PostMapping("/admin/product/update")
    @ResponseBody
    public ApiRestResponse updateProduct(@Valid @RequestBody UpdateProductRequest updateProductRequest){
        productService.updateProduct(updateProductRequest);
        return ApiRestResponse.success();
    }

    @PostMapping("/admin/product/delete")
    @ResponseBody
    public ApiRestResponse deleteProduct(Integer id){
        productService.deleteProduct(id);
        return ApiRestResponse.success();
    }

    @PostMapping("/admin/product/batchUpdateSellStatus")
    @ResponseBody
    public ApiRestResponse batchUpdateSellStatus(@RequestParam("ids") Integer[] ids,@RequestParam("sellStatus")Integer sellStatus){
        productService.batchUpdateSellStatus(ids,sellStatus);
        return ApiRestResponse.success();
    }

    @PostMapping("/admin/product/list")
    @ResponseBody
    public ApiRestResponse adminProductList(@RequestParam("pageSize") Integer pageSize,@RequestParam("pageNum") Integer pageNum ){
        PageInfo pageInfo = productService.listForAdmin(pageNum, pageSize);
        return ApiRestResponse.success(pageInfo);
    }





}
